package com.spring.util;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 2024年4月29日
 * 文件上传工具类
 * */
public class MyNewUploadFile {
    // 上传配置
    private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
    /**
     * 单文件上传
     * @return 文件上传后的地址
     * */
    public static String uploadSingleFile(MultipartFile file,String path,String[] filetype,HttpServletRequest request) throws IOException {
        String returnPath=null;

        //获取上传文件名
        String realFilename = file.getOriginalFilename();
        //通过时间和uuid定义新文件名
        // 获取文件扩展名
        String pexfix = realFilename.substring(
                        realFilename.lastIndexOf("."), realFilename.length())
                .toLowerCase();
        //判断文件上传的扩展名是否符合要求
        if(!IsAllowFile(filetype,pexfix)){
            //不符合要求则直接返回
            System.out.println("上传文件格式不符");
            return returnPath;
        }

        // 文件名根据时间自定义
        Date dNowDate = new Date();
        SimpleDateFormat ft = new SimpleDateFormat(
                "yyyyMMddhhmmss");
        String saveFileName = ft.format(dNowDate) + getUUID()
                + pexfix;
        //命名上传路径
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String uploadSaveFolder = format.format(new Date());

        // 这个路径相对当前应用的目录
        String uploadPath = setrootPath(request, "WEB-INF\\"+path + "\\" + uploadSaveFolder);
        System.out.println("实际上传目录：" + uploadPath);
        File uploadDir = new File(uploadPath);
        //判断目录是否存在，不存在则创建目录
        if (!uploadDir.exists()) {
            if(uploadDir.mkdirs()){
                System.out.println("目录创建成功！");
            }else{
                System.out.println("目录创建失败！");
            }
        }else{
            System.out.println("目录已经存在");
        }
        //存入数据库的文件路径
        String uploadFile2Database=path+"\\"+uploadSaveFolder+"\\";
        //设置文件上传路径
        String realUploadFilePath = uploadPath+saveFileName;
        //调用transferTo方法实现文件上传
        file.transferTo(new File(realUploadFilePath));

        returnPath = uploadFile2Database+saveFileName;
        System.out.println("上传后地址："+returnPath);

        return returnPath;
    }

    /**
     * 支持多文件上传
     * */
    public List<String> uploadMultiFile(MultipartHttpServletRequest  multiRequest,HttpServletRequest request){
        return null;
    }

    // 初始化文件上传路径
    private static String setrootPath(HttpServletRequest req, String mypath) {
        // 获得服务器的名字
        String serverName = req.getServerName();
        // 取得互联网程序的绝对地址
        String realPath = req.getRealPath(serverName);
        realPath = realPath.substring(0, realPath.lastIndexOf("\\"));
        String rootPath = realPath + "\\" + mypath + "\\";
        return rootPath;
    }

    //随机生成uuid
    public static synchronized String getUUID() {
        UUID uuid = UUID.randomUUID();
        String str = uuid.toString();
        String uuidStr = str.replace("-", "");
        return uuidStr;
    }

    // 文件扩展名过滤方法
    private static boolean IsAllowFile(String[] mypexfix, String pexfix) {
        boolean flag = false;

        for (String s : mypexfix) {
            // 扩展名全部转小写匹配
            if (s.matches(pexfix.toLowerCase())) {
                flag = true;
            }
        }
        return flag;
    }


}
